#coding=utf-8
import socket
import threading
import time
import random
import time

def getcurrenttime():
    return time.strftime("%Y-%m-%d %H:%M:%S")

class ClientThread(threading.Thread):
    def __init__(self, client):
        threading.Thread.__init__(self)
        self.__client = client
        self.__buf = None
        self.BUFFSIZE = 1024 * 10
    def run(self):
        time.sleep(random.randint(1, 3))
        print(self.name)
        try:
            self.__buf = self.__client.recv(self.BUFFSIZE)
            self.__client.send(self.__buf)
            print(self.__buf.decode())
        except Exception as e:
            print(e)
        finally:
            print('connect close')
            # self.__client.close()



BUF_SIZE = 1024
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 8081))
server.listen(1000)
while True:
    currtime = getcurrenttime()
    print('new client begin ' + currtime + '...........................')
    client,address = server.accept()
    print('new client end ' + currtime + '...........................')

    clientThread = ClientThread(client)
    clientThread.start()
    # try:
    #     client.settimeout(10)
    #     buf = client.recv(BUF_SIZE)
    #     client.send(buf)
    #     print(buf.decode())
    # except Exception as e:
    #     print(e)
    # finally:
    #     print('connect close')
    #     client.close()
# server.close()
